﻿using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Timers;
using System.Windows.Threading;
using System.Windows.Media;

namespace BusTrackerSystem.Utility
{
    /// <summary>
    /// Contains a border, with a grid and a viewbox. A textbox is added every .1 of a second with the current time.
    /// </summary>
    public class DigitalClock : UserControl
    {
        private Viewbox _viewboxClockFace;
        private Timer _timer;

        protected override void OnInitialized(EventArgs e)
        {
            base.OnInitialized(e);

            Border border = new Border();
            border.VerticalAlignment = VerticalAlignment.Stretch;
            border.HorizontalAlignment = HorizontalAlignment.Stretch;

            Grid grid = new Grid();
            grid.RowDefinitions.Add(new RowDefinition());

            ContentPresenter content = new ContentPresenter();
            content.Content = Content;

            grid.Children.Add(content);

            _viewboxClockFace = new Viewbox();
            _viewboxClockFace.VerticalAlignment = VerticalAlignment.Stretch;
            
            grid.Children.Add(_viewboxClockFace);

            border.Child = grid;

            Content = border;

            _timer = new Timer(100);
            _timer.Elapsed += new ElapsedEventHandler(_timer_Elapsed);
            _timer.Start();
        }

        void _timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            UpdateUi(new Action(() =>
            {
                _viewboxClockFace.Child = new TextBlock() 
                {
                    TextAlignment = System.Windows.TextAlignment.Center,
                    Text = DateTime.Now.ToString("ddd d MMM yyyy HH:mm:ss")
                };
            }));
        }

        /// <summary>
        /// Cross-thread access means we have to update the UI on the UI thread.
        /// </summary>
        private void UpdateUi(Action action)
        {
            Dispatcher.Invoke(DispatcherPriority.Background, action);
        }

    }
}
